#!/usr/bin/python
#-*- coding: utf-8 -*-

from pysqlite2 import dbapi2 as sqlite

class Connect:
    '''
    '''
    def __init__(self, con):
        #try:
        if con == '':
            #con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
            #self.con = sqlite.connect("db.db", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
            self.con = sqlite.connect("sqldb", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) # create connection
        else:
            self.con = sqlite.connect(con, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) # create connection

        #http://www.py.cz/Pysqlite
        self.con.text_factory = str

        #except:
        #    print "I am unable to connect to the database"
        self.cur = self.con.cursor()

class Query(Connect):
    ''' '''
    def __init__(self, q, con=''):
        Connect.__init__(self, con)
        self.sql = q
        self.cur.execute(q)
        self.con.commit()               #

    def __getitem__(self, index):
        row = ''
        while row <> None:
            row = self.cur.fetchone() # cur.fetchall() or cur.fetchone()
            if row <> None: 
                return row
            else:
                raise IndexError



#cur.execute("create table test(d date, ts timestamp)")
#cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
#cur.execute("select d, ts from test")
#con.commit()
#cur.execute("select * from test;")
#row = cur.fetchone()

#print today, "=>", row[0], type(row[0])
#print now, "=>", row[1], type(row[1])

#cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
#row = cur.fetchone()

#print cur.fetchone()
#rows = cur.fetchall()

#for row in cur:
#    print "current_date", row[0], #, type(row[0])
#    print "current_timestamp", row[1] #, type(row[1]) 

#cur.close()
#con.close()


if __name__ == "__main__":
    ''' '''
    #import pepe.p_sql.qry_sqlite_per_classsubclass as s
    c = 'sqldb'
    q = """select * from ta where c001 in ('0000000002', '0020000000','0010045000','0010405000')"""
    #for row in s.Query(q, c):
    for row in Query(q, c):
        print row[0], row[1]
    q = """select * from tb where c001 in ('0000001002', '0010001000','0010045100','0010405100')"""
    #for row in s.Query(q, c):
    for row in Query(q, c):
        print row[0], row[1]
